#include "StdAfx.h"
#include "SpriteRender.h"

SpriteRender& SpriteRender::get()
{
	static SpriteRender instance;
	return instance;
}

SpriteRender::SpriteRender(void)
{
}

SpriteRender::~SpriteRender(void)
{
}

void SpriteRender::Render(const RenderOption& Option)
{
	ClearRender();
	if (!InitRender(Option))
	{
		return;
	}
	SpriteFrame Frame;
	RenderFrame(Frame);
	
	if (Frame.Image)
	{
		BitmapInfo bi;		
		bi.SetWidth(256);
		bi.SetHeight(256);
		bi.SetType(BMM_TRUE_32);	//BMM_TRUE_64
		bi.SetFlags(MAP_HAS_ALPHA);
		bi.SetAspect(1.0f);
		bi.SetName("c:\\test.png");
		Frame.Image->Write(&bi);
	}
	ClearRender();

}

void SpriteRender::RenderFrame(SpriteRender::SpriteFrame& Frame)
{
	if (Frame.Image)
	{
		Frame.Image->DeleteThis();
		Frame.Image = NULL;
	}
	// create a bitmap for this frame.
	BitmapInfo bi;		
	bi.SetWidth(256);
	bi.SetHeight(256);
	bi.SetType(BMM_TRUE_32);	//BMM_TRUE_64
	bi.SetFlags(MAP_HAS_ALPHA);
	bi.SetAspect(1.0f);

	Frame.Image = TheManager->Create(&bi);
	

	// Display the bitmap
	Frame.Image->Display(_T("Test"));

	// 
	m_Interface->OpenCurRenderer(NULL, m_Viewport);
	m_Interface->CurRendererRenderFrame(m_Interface->GetTime(), Frame.Image);
	m_Interface->CloseCurRenderer();	
}

BOOL SpriteRender::InitRender(const RenderOption& Option)
{
	m_Interface = GetCOREInterface();
	if (!m_Interface)
	{
		return FALSE;
	}
	m_Viewport = m_Interface->GetActiveViewport();
	if (!m_Viewport)
	{
		return FALSE;
	}

	if (Option.RootNodeName.empty() || Option.CameraNodeName.empty())
	{
		return FALSE;
	}
	
	m_RootNode = m_Interface->GetINodeByName(Option.RootNodeName.c_str());
	m_CameraNode = m_Interface->GetINodeByName(Option.CameraNodeName.c_str());
	if(!m_RootNode || !m_CameraNode)
	{
		return FALSE;
	}
	//m_Viewport->
	m_Viewport->SetViewCamera(m_CameraNode);

	return TRUE;
}

void SpriteRender::ClearRender()
{
	if (m_Interface)
	{
		if (m_Viewport)
		{
			m_Interface->ReleaseViewport(m_Viewport);
			m_Viewport = NULL;
		}
		m_Interface = NULL;
	}
	m_CameraNode = NULL;
	m_RootNode = NULL;
}